//
//  SJTxtDetailViewController.m
//  WSL
//
//  Created by CJ on 2017/12/1.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJTxtDetailViewController.h"
#import "SJWordItem.h"
#import "SJExtraItem.h"
#import "SJFunctionBar.h"
#import "SJOtherFunctionBar.h"
#import "SJSpaceStationAddApi.h"
#import "SJEditTxtViewController.h"

@interface SJTxtDetailViewController () <SJFunctionBarDelegate, SJOtherFunctionBarDelegate>
/////////  navigationBar
@property (nonatomic, strong) UIView *navigationBarView;
@property (nonatomic, strong) UITextView *txtTextView;
@property (strong, nonatomic) UIView *bgView;
@property (strong, nonatomic) SJExtraItem *extraItem;
@property (strong, nonatomic) NSMutableArray *optionArray;

@end

@implementation SJTxtDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)dealloc {
    SJLogFunc;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didEditWordNotification:(NSNotification *)notification {
    
    SJWordItem *item = notification.userInfo[@"item"];
    
    self.item = item;
    
    [self analysisItem:self.item];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self analysisItem:self.item];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEditWordNotification:) name:SJDidEditWordNotification object:nil];
    
}

- (void)analysisItem:(SJWordItem *)item {
    
    self.extraItem = [SJExtraItem modelWithJSON:item.extra];
    
//    self.txtTextView.text = self.item.content;
    
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:SJLayoutFrame(6)];
    UIColor *color = [UIColor whiteColor];
    UIFont *font = [UIFont systemFontOfSize:SJTxtSize];
    NSAttributedString *string = [[NSAttributedString alloc] initWithString:self.item.content attributes:@{NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font}];
    
    self.txtTextView.attributedText = string;
    
    if ([self.extraItem.align isEqualToString:@"2"]) {
        _txtTextView.textAlignment = NSTextAlignmentCenter;
    } else {
        _txtTextView.textAlignment = NSTextAlignmentJustified;
    }

}

- (void)setupUI {
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }

    
    [self.view addSubview:self.bgView];
    self.bgView.sd_layout
    .topSpaceToView(self.navigationBarView, SJMargin)
    .leftSpaceToView(self.view, SJMargin)
    .rightSpaceToView(self.view, SJMargin)
    .bottomSpaceToView(self.view, SJMargin);
    
    [self.view addSubview:self.txtTextView];
    self.txtTextView.sd_layout
    .topSpaceToView(self.navigationBarView, SJMargin)
    .leftSpaceToView(self.view, SJMargin)
    .rightSpaceToView(self.view, SJMargin)
    .bottomSpaceToView(self.view, SJMargin);
    
    
//    if (self.hasMore) {
//        
//        UIButton * moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [moreButton setImage:[UIImage imageNamed:@"detail_btn_more_nor"] forState:UIControlStateNormal];
//        [moreButton addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
//        
//        [self.view addSubview:moreButton];
//        moreButton.sd_layout
//        .bottomSpaceToView(self.view, SJLayoutFrame(5))
//        .rightSpaceToView(self.view, SJLayoutFrame(5))
//        .heightIs(SJLayoutFrame(40))
//        .widthIs(SJLayoutFrame(40));
//    }
}


- (void)functionBar:(SJFunctionBar *)uploadBar didSelectItemAtIndex:(NSInteger)index {
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 编辑
            [weakSelf editItem];
        }
        
        if (index == 1) { // 移入收藏
            [weakSelf moveToFavorite];
        }
        
        if (index == 2) { // 副本收藏
            [weakSelf cpToFavorite];
        }
        
    }];
}

- (void)otherFunctionBar:(SJOtherFunctionBar *)uploadBar didSelectItemAtIndex:(NSInteger)index {
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 副本收藏
            if ([weakSelf.item.can_fav isEqualToString:@"1"]) {
                
                [SVProgressHUD showInfoWithStatus:@"内容受作者保护"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                return;
            }
            
            [weakSelf cpToFavorite];
        }
        
    }];
}


- (void)editFilter {
    
    // 检索
    int max_t = 0;
    for (SJWordItem *item in self.dataArray) {
        
        if ([item.t intValue] >= max_t) {
            max_t = [item.t intValue] + [item.h intValue];
        }
    }
    
    NSMutableArray *arrlt = [NSMutableArray array]; // 二维
    int max_w = SJItemCount;
    for (int i = 0; i < max_t + max_w; i++) {
        
        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [arrlt addObject:arrl];
        
        for (int j = 0; j < max_w; j++) {
            arrlt[i][j] = @0;
        }
    }
    
    for (SJWordItem *item in self.dataArray) {
        
        if (item == self.item) {
            continue;
        }
        
        int t = [item.t intValue];
        int l = [item.l intValue];
        int w = [item.w intValue];
        int h = [item.h intValue];
        
        for (int i = t; i < t + h; i++) {
            
            for (int j = l; j < l + w; j++) {
                arrlt[i][j] = @1;
            }
        }
    }
    
    int l2r = 0;
    NSMutableArray *optArray = [NSMutableArray array];
    
    if ([self.item.t intValue] >= arrlt.count - max_w) {
        
        int maxOptW = max_w - [self.item.l intValue];
        int maxOptH = max_w;
        
        for (int i = 0; i < maxOptH; i++) {
            
            for (int j = 0; j < maxOptW; j++) {
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = [NSString stringWithFormat:@"%d", i + 1];
                dict[@"w"] = [NSString stringWithFormat:@"%d", j + 1];
                [optArray addObject:dict];
            }
        }
        
    } else {
        
        for (int i = [self.item.l intValue]; i < max_w; i++) { // 第1行
            
            if ([arrlt[[self.item.t intValue]][i] isEqualToNumber: @0]) {
                
                l2r = i - [self.item.l intValue] + 1;
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = @"1";
                dict[@"w"] = [NSString stringWithFormat:@"%d", l2r];
                [optArray addObject:dict];
                
            } else {
                break;
            }
        }
        
        for (int n = 1; n < max_w; n++) { // 2 ~ max_w 行
            
            for (int i = [self.item.l intValue]; i < max_w; i++) {
                
                if ([arrlt[[self.item.t intValue] + n][i] isEqualToNumber: @0]) {
                    
                    if (i - [self.item.l intValue] + 1 <= l2r) {
                        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                        dict[@"h"] = [NSString stringWithFormat:@"%d", n + 1];
                        dict[@"w"] = [NSString stringWithFormat:@"%d", i - [self.item.l intValue] + 1];
                        [optArray addObject:dict];
                    } else {
                        break;
                    }
                    
                } else {
                    l2r = i - [self.item.l intValue];
                    break;
                }
            }
        }
    }
    
    if (optArray.count == 0) {
        return;
    }
    
    self.optionArray = optArray;
    
}


- (void)editItem {
    
    [self editFilter];
        
    SJEditTxtViewController *editVC = [SJEditTxtViewController new];
    editVC.item = self.item;
    editVC.optionArray = self.optionArray;
    editVC.popToVc = self.popToVc;
    [self.navigationController pushViewController:editVC animated:YES];
    
}

- (void)cpToFavorite {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = self.item.ID;
    parameters[@"source"] = @"6";
    
    SJSpaceStationAddApi *api = [[SJSpaceStationAddApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}

- (void)moveToFavorite {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = self.item.ID;
    parameters[@"source"] = @"3";
    
    SJSpaceStationAddApi *api = [[SJSpaceStationAddApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
//            [self.dataArray removeObject:self.selectedItem];
//            [self.collectionView reloadData];
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}


- (void)moreAction {
    
    if ([self.item.is_me isEqualToString:@"1"]) { // 自己
        
        SJFunctionBar *functionBar = [[SJFunctionBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(85))];
        functionBar.delegate = self;
        
        [LEEAlert actionsheet].config
        .LeeAddCustomView(^(LEECustomView *custom) {
            custom.view = functionBar;
        })
        .LeeCornerRadius(SJCornerRadius)
        .LeeHeaderColor([UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]])
        .LeeActionSheetBottomMargin(SJLayoutFrame(7))
        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
            return SJScreenW - SJLayoutFrame(14);
        })
        .LeeHeaderInsets(UIEdgeInsetsZero)
        .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
        .LeeShow();
        
    } else {
        
        SJOtherFunctionBar *functionBar = [[SJOtherFunctionBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(85))];
        functionBar.delegate = self;
        
        [LEEAlert actionsheet].config
        .LeeAddCustomView(^(LEECustomView *custom) {
            custom.view = functionBar;
        })
        .LeeCornerRadius(SJCornerRadius)
        .LeeHeaderColor([UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]])
        .LeeActionSheetBottomMargin(SJLayoutFrame(7))
        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
            return SJScreenW - SJLayoutFrame(14);
        })
        .LeeHeaderInsets(UIEdgeInsetsZero)
        .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
        .LeeShow();
    }
    
}


#pragma mark - getter


- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
    }
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (UITextView *)txtTextView {
    
    if (!_txtTextView) {
        
        _txtTextView = [UITextView new];
        _txtTextView.font = [UIFont systemFontOfSize:SJLayoutFrame(14)];
        _txtTextView.textColor = SJColorHexString(@"#ffffff");
        _txtTextView.backgroundColor = [UIColor clearColor];
        _txtTextView.textAlignment = NSTextAlignmentJustified;
        _txtTextView.editable = NO;
    }
    return _txtTextView;
}

- (UIView *)bgView {
    
    if (!_bgView) {
        
        _bgView = [UIView new];
        _bgView.sd_cornerRadius = @(SJCornerRadius);
        _bgView.backgroundColor = SJColorHexString(@"#ffffff");
        _bgView.alpha = 0;
        
    }
    return _bgView;
}

@end
